package com.ht.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

/**
 * 处理base64格式图片
 */
@Slf4j
public class TranBaseToImgUtil {

    /**
     * 将base64格式图片存为jpg格式
     *
     * @param imgStr     base64图片字符串
     * @param uploadpath 保存跟目录
     * @return 保存相对地址
     */
    public static String GenerateImage(String imgStr, String uploadpath) throws Exception {
        if (imgStr == null) {
            return ""; // 图像数据为空
        }
        Base64.Decoder decoder = Base64.getDecoder();
        // Base64解码,对字节数组字符串进行Base64解码并生成图片
        imgStr = imgStr.replaceAll(" ", "+");
        // System.out.println(imgStr);
        byte[] b = decoder.decode(imgStr.replace("data:image/jpeg;base64,", ""));
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {// 调整异常数据
                b[i] += (byte) 256;
            }
        }
        try {
            String bizPath = "files";
            String nowDay = new SimpleDateFormat("yyyyMMdd").format(new Date());
            File file = new File(uploadpath + File.separator + bizPath + File.separator + nowDay);
            if (!file.exists()) {
                boolean r = file.mkdirs();// 创建文件根目录
                if (!r) {
                    return "";
                }
            }
            String tempFileName = DateUtils.getDataString(DateUtils.yyyymmddhhmmss) + random(8);// 设置上传后文件名
            String savePath = file.getPath() + File.separator + tempFileName + ".jpg";
            File savefile = new File(savePath);
            FileCopyUtils.copy(b, savefile);
            String dbpath = bizPath + File.separator + nowDay + File.separator + tempFileName + ".jpg";
            if (dbpath.contains("\\")) {
                dbpath = dbpath.replace("\\", "/");
            }
            return dbpath;
        } catch (IOException e) {
            log.error("上传失败", e);
        }
        return "上传失败";
    }

    /**
     * 设置随机数
     */
    public static String random(int bit) {
        if (bit == 0)
            bit = 6; // 默认6位
        // 因为o和0,l和1很难区分,所以,去掉大小写的o和l
        String str = "";
        str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz";// 初始化种子
        return RandomStringUtils.random(bit, str);
    }

}
